<template>
  <scroll-view
    scroll-y
    class="viewport"
    :style="{ paddingBottom: safeAreaInsets!.bottom + 50 + 'px' }"
  >
    <!-- 收货地址 -->
    <navigator
      v-if="defaultAddress"
      class="shipment"
      hover-class="none"
      url="/pagesMember/address/address?from=order"
    >
      <view class="user">{{
        orderStore.selectAddress.receiver + ' ' + orderStore.selectAddress.contact
      }}</view>
      <view class="address"
        >{{ orderStore.selectAddress.fullLocation + ' ' + orderStore.selectAddress.address }}
      </view>
      <text class="icon icon-right"></text>
    </navigator>
    <navigator
      v-else
      class="shipment"
      hover-class="none"
      url="/pagesMember/address/address?from=order"
    >
      <view class="address"> 请选择收货地址 </view>
      <text class="icon icon-right"></text>
    </navigator>
    <!-- 支付方式 -->
    <view class="payment_box" @click="changePayMay">
      <view>支付方式</view>
      <view class="way_box">
        <!-- 支付图标 -->
        <image :src="selectPayMay.src" mode="widthFix" style="width: 36rpx; margin-right: 15rpx" />
        {{ selectPayMay.name }}
      </view>
    </view>
    <!-- 商品信息 -->
    <view class="goods">
      <navigator
        v-for="item in preOrderData.goods"
        :key="item.skuId"
        :url="`/pages/goods/goods?id=${item.id}`"
        class="item"
        hover-class="none"
      >
        <image class="picture" :src="item.picture" />
        <view class="meta">
          <view class="name ellipsis">{{ item.name }}</view>
          <view class="attrs">{{ item.attrsText }}</view>
          <view class="prices">
            <view class="pay-price symbol">{{ item.payPrice }}</view>
            <view class="price symbol">{{ item.price }}</view>
          </view>
          <view class="count">x{{ item.count }}</view>
        </view>
      </navigator>
    </view>

    <!-- 配送及留言 -->
    <view class="related">
      <view class="item">
        <text class="text">配送时间</text>
        <picker :range="deliveryList" range-key="text" @change="onChangeDelivery">
          <view class="icon-fonts picker">{{ activeDelivery.text }}</view>
        </picker>
      </view>
      <view class="item">
        <text class="text">订单备注</text>
        <input
          class="input"
          :cursor-spacing="30"
          placeholder="选题，建议留言前先与商家沟通确认"
          v-model="buyerMessage"
        />
      </view>
    </view>

    <!-- 支付金额 -->
    <view class="settlement">
      <view class="item">
        <text class="text">商品总价: </text>
        <text class="number symbol">{{
          ((preOrderData!.summary || {}).totalPrice || 0).toFixed(2)
        }}</text>
      </view>
      <view class="item">
        <text class="text">运费: </text>
        <text class="number symbol">{{
          ((preOrderData!.summary! || {}).postFee || 0).toFixed(2)
        }}</text>
      </view>
    </view>
  </scroll-view>

  <!-- 吸底工具栏 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="total-pay symbol">
      <text class="number">{{
        ((preOrderData!.summary || {}).totalPayPrice || 0).toFixed(2)
      }}</text>
    </view>
    <view class="button" :class="{ disabled: !defaultAddress }" @click="submitOrder">
      提交订单
    </view>
  </view>

  <!-- 支付方式弹出层 -->
  <uni-popup ref="payPopupRef" type="bottom" background-color="#fff">
    <view class="popup_box">
      <view class="title"
        >支付方式
        <text class="icon-cuo" @click="closePayPopup"></text>
      </view>
      <view class="payMay_box">
        <view
          class="payMay_item"
          v-for="item in payMayList"
          :key="item.name"
          :class="{ disabled: item.isSupport === 0 }"
          @click="changeMay(item)"
        >
          <image :src="item.src" mode="widthFix" class="payMay_icon" />
          <text>{{ item.name }}</text>
          <image
            src="@/static/images/dui.png"
            mode="widthFix"
            class="select_box"
            v-show="item.isSelected === 1"
          />
          <text v-show="item.isSupport === 0" class="tip_box">本次下单不支持货到付款</text>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
// 引入接口
import { againBuyAPI, getPreOrderAPI, postSubmitOrderAPI } from '@/api/order'
// 引入ts类型
import type { preOrderType, goodsType, submitOrderParamsType } from '@/types/order'
// 引入orde仓库
import { useOrderStore } from '@/store/modules/order'
// 创建仓库对象
const orderStore = useOrderStore()
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 订单备注
const buyerMessage = ref('')
// 接收传递过来的参数
const query = defineProps<{
  orderId?: string
  nowBuyOrder?: string
}>()
// 配送时间
const deliveryList = ref([
  { type: 1, text: '时间不限 (周一至周日)' },
  { type: 2, text: '工作日送 (周一至周五)' },
  { type: 3, text: '周末配送 (周六至周日)' },
])
// 当前配送时间下标
const activeIndex = ref(0)
// 当前配送时间
const activeDelivery = computed(() => deliveryList.value[activeIndex.value])
// 修改配送时间
const onChangeDelivery = (ev: any) => {
  activeIndex.value = ev.detail.value
}
// 预付订单
const preOrderData = ref<preOrderType>({} as preOrderType)
// 获取预付订单的函数
const getPreOrderData = async () => {
  const res = await getPreOrderAPI()
  if (res.code === '1') {
    preOrderData.value = res.result
    // 循环, 找出默认地址项
    const index = preOrderData.value.userAddresses.findIndex((item) => item.isDefault === 1)
    if (index !== -1) {
      // 将找出来的默认地址存到仓库中
      orderStore.setAddress(preOrderData.value.userAddresses[index])
    }
  }
}
// 计算出是否已经选中地址
const defaultAddress = computed(() => {
  return orderStore.selectAddress.id ? true : false
})
// 支付方式的ts类型
type payMayType = {
  payType: number // 1 在线支付  2 货到付款
  isSelected: number // 1 选中, 0 未选中
  name: string
  src: string
  isSupport: number // 1  支持,  0 不支持
  payChannel?: number // 1 微信支付   2 支付宝支付
}
// 选中的支付方式
const selectPayMay = ref<payMayType>({
  payType: 1,
  isSelected: 1,
  name: '微信支付',
  src: '../../static/images/weixin.png',
  isSupport: 1,
  payChannel: 1,
})
// 支付方式列表
const payMayList = ref<payMayType[]>([
  {
    payType: 1,
    isSelected: 1,
    name: '微信支付',
    src: '../../static/images/weixin.png',
    isSupport: 1,
    payChannel: 1,
  },
  {
    payType: 1,
    isSelected: 0,
    name: '支付宝支付',
    src: '../../static/images/zhifubao.png',
    isSupport: 1,
    payChannel: 2,
  },
  {
    payType: 2,
    isSelected: 0,
    name: '货到付款',
    src: '../../static/images/money.png',
    isSupport: 0,
  },
])
// 支付方式弹出层的ref对象
const payPopupRef = ref()
// 点击支付方式的回调
const changePayMay = () => {
  payPopupRef.value.open()
}
const closePayPopup = () => {
  payPopupRef.value.close()
}
const changeMay = (item: payMayType) => {
  if (item.isSupport !== 0) {
    // 可以选择的支付方式
    // 排他思想
    payMayList.value.forEach((item) => (item.isSelected = 0))
    item.isSelected = 1
    selectPayMay.value = item
    // 关闭弹出层
    payPopupRef.value.close()
  }
}
// 提交订单按钮的回调
const submitOrder = async () => {
  if (!defaultAddress.value) {
    return
  }
  // 整合参数
  const goods = preOrderData.value.goods.map((item: goodsType) => {
    return {
      skuId: item.skuId,
      count: item.count,
    }
  })
  const params: submitOrderParamsType = {
    goods,
    addressId: orderStore.selectAddress.id,
    deliveryTimeType: activeIndex.value + 1,
    buyerMessage: buyerMessage.value,
    payType: selectPayMay.value.payType,
    payChannel: selectPayMay.value.payType === 1 ? selectPayMay.value.payChannel! : 0,
  }
  // 调用接口
  const res = await postSubmitOrderAPI(params)
  if (res.code === '1') {
    uni.redirectTo({
      url: `/pagesOrder/orderDetail/orderDetail?id=${res.result.id}`,
    })
  }
}
// 获取再次购买数据的函数
const agaignOrderData = async () => {
  const res = await againBuyAPI(query.orderId!)
  if (res.code === '1') {
    preOrderData.value = res.result
  }
}
onLoad(() => {
  if (query.orderId) {
    agaignOrderData()
  } else if (query.nowBuyOrder) {
    preOrderData.value = JSON.parse(query.nowBuyOrder)
    if (preOrderData.value.userAddresses.length > 0) {
      orderStore.setAddress(preOrderData.value.userAddresses[0])
    }
  } else {
    getPreOrderData()
  }
})
</script>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}
.viewport {
  flex: 1;
  overflow-y: scroll;
}

.symbol::before {
  content: '¥';
  font-size: 80%;
  margin-right: 5rpx;
}

.shipment {
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 84rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: url(../../static/images/address.png) 20rpx center / 50rpx no-repeat #fff;
  position: relative;

  .icon {
    font-size: 24rpx;
    color: #333;
    transform: translateY(-50%);
    position: absolute;
    top: 50%;
    right: 20rpx;
  }

  .user {
    color: #333;
    margin-bottom: 5rpx;
  }

  .address {
    color: #666;
  }
}
.payment_box {
  display: flex;
  justify-content: space-between;
  margin: 0 20rpx;
  padding: 30rpx 20rpx;
  border-radius: 10rpx;
  background-color: #fff;
  font-size: 26rpx;
  color: #666;
  .way_box {
    display: flex;
    align-items: center;
    position: relative;
    padding-right: 24rpx;
    font-weight: 700;
    color: #000;
    &::after {
      position: absolute;
      top: 10rpx;
      right: 0;
      font-family: 'iconfont';
      content: '\e612';
      font-size: 18rpx;
    }
  }
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrs {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #cf4444;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    text-align: right;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #999;
  }

  .item .text {
    width: 125rpx;
  }

  .picker {
    position: relative;
    padding-right: 18rpx;
    color: #666;
  }

  .picker::after {
    position: absolute;
    top: 10rpx;
    right: 0;
    font-size: 18rpx;
    font-family: 'iconfont';
    content: '\e612';
  }
}

/* 结算清单 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #cf4444;
  }
}

/* 吸底工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .total-pay {
    font-size: 40rpx;
    color: #cf4444;

    .decimal {
      font-size: 75%;
    }
  }

  .button {
    width: 220rpx;
    text-align: center;
    line-height: 72rpx;
    font-size: 26rpx;
    color: #fff;
    border-radius: 72rpx;
    background-color: #ff3304;
  }

  .disabled {
    opacity: 0.6;
  }
}
.popup_box {
  padding-bottom: 200rpx;
  .title {
    position: relative;
    padding: 20rpx 0;
    text-align: center;
    font-weight: 700;
    .icon-cuo {
      position: absolute;
      right: 40rpx;
      color: #666;
    }
  }
  .payMay_box {
    padding: 0 40rpx;
    font-size: 28rpx;
    .payMay_item {
      position: relative;
      display: flex;
      align-items: center;
      padding: 40rpx 0;
      border-bottom: 2rpx solid #eee;
      .payMay_icon {
        width: 36rpx;
        margin-right: 30rpx;
      }
      .select_box {
        position: absolute;
        right: 0;
        width: 36rpx;
      }
      .tip_box {
        position: absolute;
        right: 0;
      }
    }
    .disabled {
      opacity: 0.6;
    }
  }
}
</style>
